<script>
	import store from 'store/index.js';
	import util from 'utils/utils.js';
	import * as api from '@/api/login';
	import request from '@/utils/httpRequset/js_sdk/request';
	import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update';
	import {
		settingLocationAuth
	} from '@/api/device/'

	// 引入原生插件
	// const pushLive = uni.requireNativePlugin('service-keep-live');

	export default {
		globalData: {
			testl: 'hello',
			devices: [], //搜索到的ei设备列表
			deviceId: '',
			serviceId: '',
			characteristicId: '',
			count1: 0,
			notOperatedCount: 0, //规定时间内未操作就断开连接
			operationTimer: null,
			lastDeviceId: '', //上次连接时的设备id
			isDeteDeviceState: false, //是否检测设备的状态
		},
		onLaunch: function() {
			console.log('App Launch');
			let that = this;
			uni.getSystemInfo({
				success(res) {
					// console.log('1: system platom>>', res);
					try {
						//将设备的UUID存入store中
						that.$store.commit('deviceUUID', res.deviceId);
						// 判断手机操作系统  开启服务
						if (res.platform == 'android') {
							// 检查更新
							console.log('update');
							checkUpdate(false);
							// that.goStartService();
							// pushLive.closeService(function(res) {
							// 	console.log(res)
							// });
						}
					} catch (e) {
						// error
					}
				}
			});
			// 查看所有权限

			try {
				const value = uni.getStorageSync('userInfo');
				if (value) store.commit('userInfo', value);

				const mappingRatio = uni.getStorageSync('mappingRatio');
				if (mappingRatio) store.commit('SET_MappingRatio', mappingRatio);

				const deepWarningTimes = uni.getStorageSync('deepWarningTimes');
				if (deepWarningTimes) store.commit('SET_DeepWarningTimes', deepWarningTimes);
			} catch (e) {
				// error
				console.log('error', e);
			}
			// 监听网络情况  ..首次先检查
			uni.getNetworkType({
				success(res) {
					// console.log(res);
					if (res.networkType == 'none') {
						store.commit('changeNetStatus', false);
						uni.showToast({
							title: '请检查网络连接',
							icon: 'none',
							duration: 3000
						});
					}
				}
			});
			// listening net state...
			uni.onNetworkStatusChange(function(res) {
				store.commit('changeNetStatus', res.isConnected);
				if (!res.isConnected) {
					uni.showToast({
						title: '请检查网络连接',
						icon: 'none'
					});
				}
			});
			const appAuthorizeSetting = uni.getAppAuthorizeSetting()
			console.log('appAuthorizeSetting: ', appAuthorizeSetting);
		},
		onShow: function() {
			console.log('App Show');
		},
		onHide: function() {
			console.log('App Hide');
		},
		methods: {
			getErpToken() {
				return new Promise((resolve, reject) => {
					let that = this;
					let data = {
						params: {
							// annoyFree
							// 123456
							userName: 'annoyFree',
							userSecret: '123456'
						},
						action: 'getToken'
					};
					api.getToken(data).then(function(res) {
						console.log('getErpToken ', res)
						if (res.data.code === 2000) {
							resolve(res.data.data.token);
						} else {
							reject(false);;
						}
					}).catch(function(error) {
						console.log('getErpToken fail', error)
						reject(false);;
					});
				});
			},
			// 保活
			goStartService() {
				console.log('toservice');
				// wakeLock.wakeLock();
				let obj = {
					title: '免烦脑',
					content: '正在后台运行',
					mode: 1,
					isShow: true
				};
				pushLive.startService(obj, function(res) {
					console.log('开始服务', res);
				});
			},
			//以轮询的方式获取tokenId
			getTokenIdPolling() {
				// this.getTokenId();
				try {
					let Timer = setInterval(this.getTokenId, 600000);
				} catch (e) {
					//TODO handle the exception
					console.error(`token catch>${e}`);
				}
			},

			getTokenId() {
				let that = this;
				let userInfo = store.state.userInfo;
				let currentUser = userInfo.currentUser;
				let appId = currentUser.appId;
				let appSecret = currentUser.appSecret;
				let userId = currentUser.userId;
				let data = {
					action: 'getToken',
					userId: userId,
					params: {
						appId: appId,
						appSecret: appSecret
					}
				};
				api.getToken(data)
					.then(function(res) {
						console.log('getToken>>>', res);
						if (res.data.code == 2000) {
							store.commit('token', res.data.data.token);
						} else if (res.data.code == 2001) {
							that.$toast('登录已过期,请重新登录!');
							if (res.data.message == '该账户已在另一设备端登陆') {
								// 此处加一个强制退出功能
								let t = setTimeout(() => {
									clearTimeout(t);
									that.exitLogin()
								}, 1000);
							}
						}
					})
					.catch(function(error) {
						console.log('get TokenId fail', error);
					});
			},
			async requestAgain(url, data) {
				console.log('token过期,重新请求!');
				try {
					let res = await this.getTokenAgain();
					if (res) return request.post(url, data);
				} catch (e) {
					return Promise.reject({
						statusCode: 911,
						errMsg: 'repeat fail...'
					})
					console.log('e--', e);
					//TODO handle the exception
				}
			},
			getTokenAgain() {
				return new Promise((resolve, reject) => {
					let that = this;
					let appId = store.state.userInfo.currentUser.appId;
					let appSecret = store.state.userInfo.currentUser.appSecret;
					let userId = store.state.userInfo.currentUser.userId;
					let data = {
						action: 'getToken',
						userId: userId,
						params: {
							appId: appId,
							appSecret: appSecret
						}
					};
					api.getToken(data).then(function(res) {
						console.log('getToken>>>', res);
						if (res.data.code == 2000) {
							store.commit('token', res.data.data.token);
							resolve(true);
						} else {
							reject(false);
						}
					}).catch(function(error) {
						reject(false);;
						console.log('get TokenId fail', error);
					});
				});
			},
			//弹窗
			showToast(icon, title) {
				uni.showToast({
					title: title,
					icon: icon
				});
			},
			/*
			 * 退出登录：清除缓存中所有信息、清除 store中的个人信息
			 */
			exitLogin() {
				try {
					// this.$toast('此操作不可逆 会删除缓存中得所有信息',{duration:3000});
					uni.clearStorageSync();
					store.commit('userInfo', null);
					//判断蓝牙连接状态
					if (store.state.isConnected) this.closeBLEConnection();
					let T = setTimeout(() => {
						clearTimeout(T);
						uni.reLaunch({
							url: '/pages/index/index'
						});
					}, 1000);
				} catch (e) {
					//TODO handle the exception
					console.log(e);
				}
			},
			/**
			 * 蓝牙相关的代码 。。。
			 */
			openBluetoothAdapter1(obj) {
				uni.openBluetoothAdapter({
					success: res => {
						// console.log('开启适配器成功');
						uni.getBluetoothAdapterState({
							success: res1 => {
								// console.log(res1, '蓝牙已打开');
								this.createBLEConnection(obj);
							},
							fail(error) {
								this.showToast('none', '请检查手机蓝牙是否打开!');
							}
						});
					},
					fail: err => {
						// console.log('适配器开启失败!');
						this.showToast('none', '请检查手机蓝牙是否打开!');
					}
				});
				this.onBluetoothAdapterStateChange();
			},

			// 开启蓝牙适配器
			openBluetoothAdapter() {
				uni.openBluetoothAdapter({
					success: res => {
						// console.log('开启适配器成功');
						uni.getBluetoothAdapterState({
							success: res1 => {
								this.onBluetoothAdapterStateChange();
								if (uni.getAppAuthorizeSetting().locationAuthorized == 'denied') {
									uni.showModal({
										title: '提示',
										content: '暂未开启定位权限,点击确定去开启',
										success: function(res) {
											if (res.confirm) {
												console.log('用户点击确定')
												settingLocationAuth()
											} else if (res.cancel) {
												console.log('用户点击取消')
											}
										}
									})
								} else {
									//开始搜索设备
									this.startBluetoothDeviceDiscovery();
								}
							},
							fail(error) {
								this.showToast('none', '请检查手机蓝牙是否打开!');
							}
						});
					},
					fail: err => {
						console.log('适配器开启失败!');
						store.commit('BluetoothAdapterState', false);
					}
				});
			},
			// 监听蓝牙适配器状态
			onBluetoothAdapterStateChange() {
				uni.onBluetoothAdapterStateChange(function(res) {
					// console.log('adapterState changed, now is', res.available);
					store.commit('BluetoothAdapterState', res.available);
				});
			},
			//开始搜索蓝牙设备
			startBluetoothDeviceDiscovery() {
				console.log('开始搜索');
				uni.startBluetoothDevicesDiscovery({
					services: ['6E40FFF0-B5A3-F393-E0A9-E50E24DCCA9E'], // 限定主service的uuid
					success: res => {
						console.log('startBluetoothDeviceDiscovery  success', res);
						// this.getBluetoothDevices();
						this.onBluetoothDeviceFound();
					},
					fail: res => {
						console.log('开始搜索蓝呀失败');
					}
				});
			},
			// 获取蓝牙设备列表
			getBluetoothDevices() {
				uni.getBluetoothDevices({
					success: res => {
						console.log('获取生效时蓝牙设备成功:', res);
						// console.log(JSON.stringify(res));
					},
					fail: e => {
						console.log('获取蓝牙设备错误，错误码：' + e.errCode);
						if (e.errCode !== 0) {
							initTypes(e.errCode);
						}
					}
				});
			},
			//检测蓝牙设备状态
			deteDeviceState(flag) {
				this.globalData.isDeteDeviceState = flag
				this.startBluetoothDeviceDiscovery()
			},
			// 发现外围设备（监听）
			onBluetoothDeviceFound() {
				var that = this;
				var timer = null;

        // var serachDeviceName = 'EI-B100_b165179bebd19f0';
				var serachDeviceName = 'EI-B100';
				// var serachDeviceName = 'EI-B100_8bc08716e7dcfa2';
				uni.onBluetoothDeviceFound(res => {
					// console.log('发现的蓝牙设备', res);
					if (res.devices.length != 0) {
						res.devices.forEach(device => {
							if (device.name.indexOf(serachDeviceName) != -1) {
								console.log('EI的设备', device.name);
								that.globalData.devices.push(device);
							}
						});
					}
				});
				//成功与否，都关闭蓝牙搜索
				timer = setTimeout(() => {
					console.log('倒计时结束 停止搜索');
					that.stopBluetoothDevicesDiscovery();
					clearTimeout(timer);
					// 这里做一些搜索不到设备的操作 延时
				}, 2000);
			},
			// 关闭蓝牙扫描状态
			stopBluetoothDevicesDiscovery() {
				let that = this;
				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						console.log('stopBluetoothDevicesDiscovery  success ', that.globalData.devices);
						if (that.globalData.isDeteDeviceState) {
							let findDevices = []
							that.globalData.devices.forEach((item) => {
								findDevices.push(item.deviceId)
							})
							console.log('lastDeviceId>>>' + that.globalData.lastDeviceId);
							if (findDevices.indexOf(that.globalData.lastDeviceId) == -1) {
								uni.$emit('ble-device-state', {
									msg: '设备已关机'
								});
							} else {
								uni.$emit('ble-device-state', {
									msg: '连接已断开'
								});
							}
							return
						}
						if (that.globalData.devices.length == 1) {
							that.createBLEConnection(that.globalData.devices[0]);
							store.commit('isEiDevice', true);
						} else if (that.globalData.devices.length > 1) {
							console.log('搜索到多个EI的设备');
							uni.showToast({
								title: '发现多个设备',
								icon: 'none'
							});
						} else {
							console.log('没找到EI的设备!!!');
							store.commit('isEiDevice', false);
							const appAuthorizeSetting = uni.getAppAuthorizeSetting()
							console.log('appAuthorizeSetting>>', appAuthorizeSetting);
							if (appAuthorizeSetting.locationAuthorized == 'denied') {
								that.$toast('请在设置中允许定位权限')
								setTimeout(() => {
									var Intent = plus.android.importClass("android.content.Intent");
									var Settings = plus.android.importClass("android.provider.Settings");
									var Uri = plus.android.importClass("android.net.Uri");
									var mainActivity = plus.android.runtimeMainActivity();
									var intent = new Intent();
									intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
									var uri = Uri.fromParts("package", mainActivity.getPackageName(),
										null);
									intent.setData(uri);
									mainActivity.startActivity(intent);

								}, 2000)
							}
						}
					},
					fail(res) {
						console.log('stopBluetoothDevicesDiscovery  fail!! ');
					}
				});
			},
			// 判断定位权限是否开启
			judgeIosPermissionLocation() {
				var result = false;
				var cllocationManger = plus.ios.import("CLLocationManager");
				var status = cllocationManger.authorizationStatus();
				result = (status != 2)
				console.log("定位权限开启：" + result);
				// 以下代码判断了手机设备的定位是否关闭，推荐另行使用方法 checkSystemEnableLocation
				/* var enable = cllocationManger.locationServicesEnabled();
				var status = cllocationManger.authorizationStatus();
				console.log("enable:" + enable);
				console.log("status:" + status);
				if (enable && status != 2) {
					result = true;
					console.log("手机定位服务已开启且已授予定位权限");
				} else {
					console.log("手机系统的定位没有打开或未给予定位权限");
				} */
				plus.ios.deleteObject(cllocationManger);
				return result;
			},
			//建立连接
			createBLEConnection(device) {
				let that = this;
				let deviceId = device.deviceId;
				uni.createBLEConnection({
					deviceId,
					success(res) {
						console.log('connected success', res);
						that.getBLEDeviceServices(deviceId);
					},
					fail(res) {
						console.log('connected fail', res);
					}
				});
				console.log('在此处监听蓝牙的连接状态');
				//在此处监听蓝牙的连接状态  该方法回调中可以用于处理连接意外断开等异常情况
				uni.onBLEConnectionStateChange(function(res) {
					console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`);
					if (!res.connected) {
						that.globalData.devices = [];
					}
					that.globalData.lastDeviceId = res.deviceId
					store.commit('bleId', res.deviceId);
					store.commit('connectState', res.connected);
				});
			},
			// 获取蓝牙的服务
			getBLEDeviceServices(deviceId) {
				let that = this;
				var timer = setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: deviceId,
						success(res) {
							console.log('getBLEDeviceServices success', res);
							res.services.forEach(service => {
								if (service.uuid.indexOf('6E40FFF0') != -1) {
									// 在此处开启数据监听 （接收）
									uni.onBLECharacteristicValueChange(res => {
										console.log('监听到的蓝牙数据000>>>>>',res.value);
										uni.$emit('originalData', {
											msg: res.value
										});
										//直接将数据给store
										// store.commit('originalData', res.value);
									});
									that.getBLEDeviceCharacteristics(deviceId, service.uuid);
									return;
								}
							});
						},
						fail(res) {
							console.log('getBLEDeviceServices fail!!!', res);
						}
					});
					clearTimeout(timer);
				}, 2000);
			},

			// 获取蓝牙特征值
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				let that = this;
				console.log('获取蓝牙特征值1', serviceId);
				uni.getBLEDeviceCharacteristics({
					deviceId: deviceId,
					serviceId: serviceId,
					success(res) {
						console.log('getBLEDeviceCharacteristics success', res);
						res.characteristics.forEach(characteristic => {
							if (characteristic.properties.read) {
								uni.readBLECharacteristicValue({
									characteristicId: characteristic.uuid,
									deviceId,
									serviceId
								});
							}
							if (characteristic.properties.notify || characteristic.properties.indicate) {
								uni.notifyBLECharacteristicValueChange({
									state: true,
									deviceId,
									serviceId,
									characteristicId: characteristic.uuid,
									success(res) {
										// console.log('notifyBLECharacteristicValueChange success', res);
									}
								});
							}
							if (characteristic.properties.write) {
								that.globalData.deviceId = deviceId;
								that.globalData.serviceId = serviceId;
								that.globalData.characteristicId = characteristic.uuid;
								let t = setTimeout(() => {
									clearTimeout(t)
									that.writeBLEState(10)
								}, 800)
							}
						});
					},
					fail(res) {
						console.log('getBLEDeviceCharacteristics fail', res);
					}
				});
			},
			// 控制头环的状态 停止2 / 开始1
			writeBLEState(type) {
        console.log("当前的type状态是",type)
				return new Promise((resolve, reject) => {
					if (!store.state.isConnected) return resolve(false);
					console.log('send msg type: ', type);
					store.commit('receiptTimer', 0);
					let buffer = new ArrayBuffer(7);
					let dataView = new DataView(buffer);
					dataView.setUint8(0, 0x68);
					dataView.setUint8(1, 0x00);
					dataView.setUint8(2, 0x07);
					switch (type) {
						case 1: //开始快速
							dataView.setUint8(3, 0x01);
							dataView.setUint8(4, 0x45);
							dataView.setUint8(5, 0x2a);
							break;
						case 2: // 退出快速
							dataView.setUint8(3, 0x02);
							dataView.setUint8(4, 0x75);
							dataView.setUint8(5, 0x49);
							break;
						case 3: //深度监测
							dataView.setUint8(3, 0x03);
							dataView.setUint8(4, 0x65);
							dataView.setUint8(5, 0x68);
							break;
						case 10: //获取头环版本号
							dataView.setUint8(3, 0x10);
							dataView.setUint8(4, 0x47);
							dataView.setUint8(5, 0x3a);
							break;
						case 15: //获取头环电量
							dataView.setUint8(3, 0x0F);
							dataView.setUint8(4, 0xa4);
							dataView.setUint8(5, 0xe4);
							break;
						case 20:
							dataView.setUint8(3, 0x20);
							dataView.setUint8(4, 0x71);
							dataView.setUint8(5, 0x69);
							break;
						case 23:
							dataView.setUint8(3, 0x23);
							dataView.setUint8(4, 0x41);
							dataView.setUint8(5, 0x0A);
							break;
						case 24:
							dataView.setUint8(3, 0x24);
							dataView.setUint8(4, 0x31);
							dataView.setUint8(5, 0xED);
							break;
						case 25: //滴滴2声音
							dataView.setUint8(3, 0x25);
							dataView.setUint8(4, 0x21);
							dataView.setUint8(5, 0xCC);
							break;
						case 26://滴滴滴3声音
							dataView.setUint8(3, 0x26);
							dataView.setUint8(4, 0x11);
							dataView.setUint8(5, 0xAF);
							break;
						case 29: //头环佩戴状态
							dataView.setUint8(3, 0x29);
							dataView.setUint8(4, 0xE0);
							dataView.setUint8(5, 0x40);
							break;
					}
					dataView.setUint8(6, 0x16);
					// if (type === 23 || type === 24) {
					// 	store.commit('isRecvMsg', false);
					// 	let t = setTimeout(() => {
					// 		clearTimeout(t);
					// 		if (!store.state.isRecvMsg) {
					// 			console.log('---触发了 未收到数据');
					// 			store.commit('isCommunicationFail', true);
					// 			clearTimeout(store.state.receiptTimer);
					// 			store.commit('receiptTimer', null);
					// 		}
					// 	}, 5000);
					// }
					this.writeBLECharacteristicValue(buffer);
					if(type === 10) return;
          console.log("isReceipt",store.state.isReceipt)
					store.state.receiptTimer = setTimeout(() =>{
						if(!store.state.isConnected) return resolve(false);
						if(!store.state.isReceipt) {
							console.log('未收到回执数据--',type);
							uni.showToast({
								title:'与头环通信失败，请重启设备',
								icon: 'none'
							});
							clearTimeout(store.state.receiptTimer);
							store.commit('receiptTimer', null);
							return resolve(true);
						} else {
							store.commit('isReceipt',false);
							clearTimeout(store.state.receiptTimer);
							store.commit('receiptTimer',null);
							return resolve(true);
						}
					},1000)
				})
			},
			writeBLECharacteristicValue(value) {
				let that = this;
				that.globalData.notOperatedCount = 0
				uni.writeBLECharacteristicValue({
					deviceId: that.globalData.deviceId,
					serviceId: that.globalData.serviceId,
					characteristicId: that.globalData.characteristicId,
					value: value,
					success(res) {
						// console.log('writeBLECharacteristicValue success', res);
					},
					fail(res) {
						console.log('writeBLECharacteristicValue fail', res);
					}
				});
			},
			closeBLEConnection() {
				let deviceId = this.globalData.deviceId;
				uni.closeBLEConnection({
					deviceId: deviceId,
					success(res) {
						store.commit('isActiveDisConnect', true)
						console.log('closeBleConnection  success!!', res);
					},
					fail(err) {
						console.log('closeBleConnection  fail!!', err);
					}
				});
			},
			closeBluetoothAdapter() {
				uni.closeBluetoothAdapter({
					success(res) {
						console.log('closeBluetoothAdapter success', res);
					},
					fail(res) {
						console.log('closeBluetoothAdapter fail', res);
					}
				});
			}
		}
	};
</script>

<style>
	/*每个页面公共css */
</style>